package com.ripple.cli;

import com.ripple.client.Account;
import com.ripple.client.Client;
import com.ripple.client.transactions.ManagedTxn;
import com.ripple.client.transactions.TransactionManager;
import com.ripple.client.transport.impl.JavaWebSocketTransportImpl;
import com.ripple.core.coretypes.uint.UInt32;
import com.ripple.core.enums.TransactionFlag;
import com.ripple.core.fields.Field;
import com.ripple.core.types.known.tx.txns.AccountSet;
import org.json.JSONObject;

import static com.ripple.cli.log.Log.log;

/**
 * 为账户设置require dest tag
 * @author xinj.x
 */
public class MakeAccountSet {
    public static void main(String[] args) {
        final Client client = new Client(new JavaWebSocketTransportImpl());
        client.run(new Client.ThrowingRunnable() {
            @Override
            public void throwingRun() {
                client.connect("wss://s.altnet.rippletest.net:51233");
                Account account = client.accountFromSeed("snDjYxq3xRXm1ZFncnygxbcGwKD4B");
                TransactionManager tm = account.transactionManager();
                AccountSet accountSet = new AccountSet();
                accountSet.setFlag(UInt32.translate.fromLong(TransactionFlag.asfRequireDest));
//                accountSet.putTranslated(Field.DestinationTag, TransactionFlag.asfRequireDest);
                ManagedTxn tx = tm.manage(accountSet);
                tx.once(ManagedTxn.OnSubmitSuccess.class, response -> log("Submit success response: %s", response.engineResult()));
                tx.once(ManagedTxn.OnSubmitFailure.class, response -> log("Submit failure response: %s", response.engineResult()));
                tx.once(ManagedTxn.OnSubmitError.class, response -> log("Submit error response: %s", response.rpcerr));
                tx.once(ManagedTxn.OnTransactionValidated.class, result -> {
                    log("Transaction finalized on ledger: %s", result.ledgerIndex);
                    log("Transaction message:\n%s", prettyJSON(result.message));
                    System.exit(0);
                });
                tm.queue(tx);
            }
        });
    }private static String prettyJSON(JSONObject message) {
        return message.toString(4);
    }

}
